
const typeAll = { name: '全部', id: undefined }

export const state = () => ({
  mealTypeIds: [],
  mealTypeNames: [],
  mealType: [typeAll],
  mealTypeMaps: new Map(),

  selectedMonth: new Date(),
  schedule: [],
  scheduleMaps: {}
})

export const mutations = {
  SET_MEAL_TYPE: (state, parmas) => {
    const { mealTypeMaps, mealTypeIds, mealTypeNames } = state
    mealTypeIds.splice(0)
    mealTypeNames.splice(0)
    state.mealType = [typeAll].concat(parmas).map(item => {
      const { id, name } = item
      if (!id || !name) return false
      mealTypeMaps.set(id, item)
      mealTypeMaps.set(name, item)
      mealTypeIds.push(id)
      mealTypeNames.push(name)
      return item
    })
  },

  MONTH_CHANGE: (state, monthObj) => {
    state.selectedMonth = monthObj
  },

  SET_SCHEDULE (state, { list = [], refresh = true }) {
    if (refresh) state.scheduleMaps = {}
    const { schedule, scheduleMaps, mealTypeNames } = state
    Object.assign(schedule,
      list.map(item => {
        const { id, scheduleDate, typeNames = '' } = item
        if (typeNames) {
          const allNames = mealTypeNames.sort().join(',')
          const thisNames = Array.from(new Set(typeNames.split(','))).sort().join(',')
          const isOrder = allNames === thisNames ? 1 : 2 // 1:全部 2:部分
          Object.assign(item, { isOrder })
        }
        id && (scheduleMaps[id] = item)
        scheduleDate && (scheduleMaps[scheduleDate] = item)
        return item
      })
    )
  }
}

export const actions = {
  getMealType ({ commit }) {
    return this.$axios.post('api/mealType/query', {}).then(res => {
      if (res.data.code === '000000') commit('SET_MEAL_TYPE', res.data.data.dataList)
      return res
    })
  },

  monthChange ({ commit }, monthObj = '') {
    commit('MONTH_CHANGE', monthObj)
  },

  getSchedule ({ commit, state }, params = {}) {
    const { refresh = true } = params
    delete params.refresh
    if (!state.mealTypeNames.length) return
    const { $axios, $get, $moment } = this
    if (!params.scheduleMonth && !params.scheduleDate && (!params.maxScheduleDate && !params.minScheduleDate)) {
      const selectedMonth = $moment(state.selectedMonth || '')
      const scheduleMonth = selectedMonth.format('YYYY-MM')
      params = Object.assign({ scheduleMonth }, params)
    }
    return $axios.post('api/mealSchedule/queryDate', params)
      .then(res => commit('SET_SCHEDULE', { list: $get(res, 'data.data.dataList', []), refresh }))
  },

  delSchedule (_, id) {
    return this.$axios.delete(`api/mealSchedule/${id}`)
  },

  addSchedule (_, params) {
    return this.$axios.post('api/mealSchedule/', params)
  }
}
